package GDoc::Job::Fetch::US::Exec::Ag::CNPP::CFH;

use Moose;

use WWW::Mechanize;
use GDoc::Job;
use File::Temp;


extends 'GDoc::Job::Fetch';

my %MONTHS = ( Jan => [  1, 'January' ],   Feb => [  2, 'February' ],  Mar => [  3, 'March'     ],
               Apr => [  4, 'April'   ],   May => [  5, 'May'      ],  Jun => [  6, 'June'      ],
               Jul => [  7, 'July'    ],   Aug => [  8, 'August'   ],  Sep => [  9, 'September' ],
               Oct => [ 10, 'October' ],   Nov => [ 11, 'November' ],  Dec => [ 12, 'December'  ]
             );

sub setup { 
    my $self = shift;
    $self->_baseurl( 'http://www.cnpp.usda.gov/USDAFoodCost-Home.htm' );
    $self->_basedir( 'http://www.cnpp.usda.gov/' );
}

sub run { 
    my $self = shift;
   
    if ( $self->data->{link} ) { 
        $self->_fetch_pdf;
    } else { 
        $self->logger->info( "fetching base " . $self->_baseurl );
        my $mech = $self->_mech;
        $mech->get( $self->_baseurl );
        my @links = $mech->find_all_links( url_regex => qr{FoodPlans/\d{4}/CostofFood\w{3}\d{2}\.pdf$}i );

        foreach my $link( @links ) { 
            my $mabbr = $link->text;
            my $month = $MONTHS{$mabbr}[0];
            $link->url =~ /(?<year>\d{4})/;
            my $year = $+{year};

            next unless $month and $year;

            my $job = GDoc::Job->new( class => 'Fetch::US::Exec::Ag::CNPP::CFH',
                                      queue => $self->fetch_queue,
                                      data  => { link   => $link->url,
                                                 month  => $month,
                                                 year   => $year,
                                                 mname  => $MONTHS{$mabbr}[1]
                                               }
                                    );
            $job->submit;
        }
    }
}

sub _fetch_pdf { 
    my $self = shift;
    my %data = %{ $self->data };

    my $ident = sprintf( 'CNPP-CFH-%04d-%02d', $data{year}, $data{month} );
    my $filename = $ident . '.pdf';
    my $key = 'us/exec/ag/cnpp/' . $filename;

    $self->logger->info( "Storing $data{link} --> $key" );

    my $mech = $self->_mech;
    my $tmpf = File::Temp->new;
    $mech->get( $self->_basedir . $data{link}, ':content_file' => $tmpf->filename );

    $self->store_pdf( key      => $key,
                      datafile => $tmpf,
                      filename => $filename,
                      meta     => { description   => "Cost of Food at Home, $data{mname}, $data{year}",
                                    identifier    => $ident,
                                  }
                    );

}


1;
